package net.hn.hnms.biz.mine.company.service;

import lombok.RequiredArgsConstructor;
import net.hn.hnms.biz.mine.config.TableSwitching;
import net.hn.hnms.biz.mine.vo.ScoreVO;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author 智呈物联 nzw
 * @date 2023/1/10
 */
@Service
@RequiredArgsConstructor
public class RatingSortService {
    private final JdbcTemplate jdbcTemplate;
    private final TableSwitching tableSwitching;

    public List<ScoreVO> fireRatingSort(){
        List<ScoreVO> list = new ArrayList<>();

        String findMineCode = "select mine_code from znjc."+tableSwitching.getTableName()+" GROUP BY mine_code";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(findMineCode);
        for (Map<String,Object> map:maps){
            String mineCode = map.get("mine_code")+"";
            if (mineCode==null||"null".equals(mineCode)||"".equals(mineCode)){
                continue;
            }
            String findAllRating = "SELECT\n" +
                    "\tt2.*,\n" +
                    "\tt1.indicator_second_level_name,\n" +
                    "\tt1.indicator_third_level_name,\n" +
                    "\tt1.indicator_weight_value \n" +
                    "FROM\n" +
                    "\tznjc.ssys_indicator t1\n" +
                    "\tJOIN znjc."+tableSwitching.getTableName()+" t2 ON ( t1.indicator_first_level_code = t2.indicator_first_level_code AND t1.indicator_second_level_code = t2.indicator_second_level_code AND t1.indicator_third_level_code = t2.indicator_third_level_code ) \n" +
                    "WHERE\n" +
                    "\tt1.indicator_first_level_code = '20' \n" +
                    "\tAND data_time = ( SELECT MAX ( data_time ) FROM znjc."+tableSwitching.getTableName()+" WHERE indicator_first_level_code = '20' and mine_code = '"+mineCode+"' )";
            List<Map<String, Object>> ratings = jdbcTemplate.queryForList(findAllRating);
            //煤矿综合得分
            BigDecimal comprehensive=new BigDecimal(0);
            for (Map<String,Object> rating:ratings){
                if (rating.get("indicator_third_level_code") == null || "".equals(rating.get("indicator_third_level_code"))) {
                    String indicatorValue = rating.get("indicator_value").toString();
                    comprehensive = comprehensive.add(new BigDecimal(indicatorValue));
                }
            };
            ScoreVO scoreVO = new ScoreVO();
            scoreVO.setName(mineCode);
            scoreVO.setScore(comprehensive);

            list.add(scoreVO);
        }
        Collections.sort(list);
        return list;
    }

}
